import React, { memo, createContext, useReducer, useContext, useEffect } from 'react';
import { Reducer } from './reducer';
import {
  getTableDataList,
  addTableDataList,
  editTableDataItem,
  delTableDataItem
} from '@/api/archives/practice';
import type { stateType } from './interface';

const data: stateType = {
  payload: {
    pageNo: 1,
    pageSize: 5,
    param: {
      businessType: 1,
      receiveType: 1
    }
  },
  loading: true,
  tableData: []
};

const Context = createContext(data);

export const ContextProvider = memo((props: any) => {
  const [state, dispatch] = useReducer(Reducer, data);

  const actions = {
    async queryTableData() {
      const res = await getTableDataList(state.payload);
      const { data } = res;
      console.log(data);
    }
  };

  useEffect(() => {
    actions.queryTableData();
  }, [state.payload]);

  return <Context.Provider value={{ ...state, ...actions }}>{props.chilren}</Context.Provider>;
});

export const useUnitContext = () => {
  return useContext(Context);
};
